package top.humbleyuan.stack;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Stack;

/**
 * @Author: yuanhuanghui
 * @Date: 2020-08-07
 * @Time: 10:30
 * @Description: 是否是有效的括号组合
 */
public class Leetcode_20 {
    /**
     * 利用栈
     * 当出现闭合元素时pop比对，不满足直接false
     */
    public static void main(String[] args) {
        String s = "()";

        HashMap<Character, Character> map = new HashMap<Character, Character>() {{
            put(')', '(');
            put('}', '{');
            put(']', '[');
        }};
        Stack<Character> stack = new Stack<>();

        for(int i = 0; i < s.length(); i++) {
            Character c = s.charAt(i);

            // 闭合需要找前面的配对
            if(map.containsKey(c)) {
                if(stack.isEmpty()) {
                    System.out.println(false);
                }

                if(stack.pop() == map.get(c)) {
                    continue;
                }

                // 组合不成直接返回false,因为栈顶元素必为需要和当前元素配对的
                System.out.println(false);
            }

            stack.push(c);
        }

        System.out.println(stack.isEmpty());
    }
}
